#include <stdio.h>
#include <conio.h>
#include <windows.h>
#include <time.h>
#include "game.h"

#include "lua/lua_main.h"
#include "lua_game.h"		// methods that interface LUA and the Game

int main(int argc, char ** argv)
{
	// game init
	Game g;

	int status;
	struct Smain s;
	lua_State *L = lua_open(&g);  /* create state */
	if (L == NULL) {
		l_message(argv[0], "cannot create state: not enough memory");
		return EXIT_FAILURE;
	}
	// register system calls to LUA
	luaL_Reg f[] =
	{
		{"m_load", m_load},
		{"g_end", g_end},
		{"g_charXY", g_charXY},
		{"g_mapGet", g_mapGet},
	};
	int fSize = sizeof(f)/sizeof(luaL_Reg);
	for(int i = 0; i < fSize; ++i)
	{
		lua_register(L, f[i].name, f[i].func);
	}

	// run LUA
	s.argc = argc;
	s.argv = argv;
	status = lua_cpcall(L, &pmain, &s);
	dofile(L, "start.lua");
	report(L, status);

	g.setLua(L);

	long now, then = clock();
	float timePassed;
	// game loop (standard draw/input/update)
	while(g.isRunning())
	{
		if(_kbhit())
		{
			g.handleInput();
		}
		else
		{
			now = clock();
			timePassed = (float)(now-then)/CLOCKS_PER_SEC;
			then = now;
			g.draw();
			// give the game the number of milliseconds passed
			g.Update(timePassed);
			// throttle code
			Sleep(1);
		}
	}
	lua_close(L);
	_getch();
	// secret game release
	return 0;
}// g.~Game();